package org.wisteria.framework.core.app;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class AppModuleLoader {

	private static Logger logger = LoggerFactory.getLogger(AppModuleLoader.class);

	private List<String> modulesBasePackages = new ArrayList<>();
	private List<String> modulesDaoPackages = new ArrayList<>();

	public Properties scan() {
		try {
			PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
			Resource[] resources = pathMatchingResourcePatternResolver.getResources(ModuleConstants.MODULE_DEFINITION_RESOURCES);
			if (resources != null || resources.length > 0) {
				for (Resource resource : resources) {
					logger.info("正在加载模块[" + resource.getFilename() + "]...");

					InputStream is = resource.getInputStream();
					if (is != null) {
						Properties properties = new Properties();
						properties.load(is);
						modulesBasePackages.add(properties.getProperty(ModuleConstants.APP_MODULE_BASE_PACKAGES));
						modulesDaoPackages.add(properties.getProperty(ModuleConstants.APP_MODULE_DAO_PACKAGES));
					}
				}
			}
		} catch (IOException e) {
			logger.error(e.getMessage());
		}

		Properties configMetadata = new Properties();
		getModulesBasePackages(configMetadata);
		getModulesDaoPackages(configMetadata);
		return configMetadata;
	}

	private void getModulesBasePackages(Properties properties) {
		StringBuffer sb = new StringBuffer();
		for (String packages : modulesBasePackages) {
			if (!StringUtils.hasText(packages)) {
				continue;
			}
			sb.append(",").append(packages);
		}
		if (sb.length() > 0) {
			properties.setProperty(ModuleConstants.APP_MODULES_BASE_PACKAGES, sb.substring(1));
		}
	}

	private void getModulesDaoPackages(Properties properties) {
		StringBuffer sb = new StringBuffer();
		for (String packages : modulesDaoPackages) {
			if (!StringUtils.hasText(packages)) {
				continue;
			}
			sb.append(",").append(packages);
		}
		if (sb.length() > 0) {
			properties.setProperty(ModuleConstants.APP_MODULES_DAO_PACKAGES, sb.substring(1));
		}
	}
}
